import React, { useRef, useEffect, useState } from 'react';
import { Button, Tooltip, Spin } from 'antd';
import {
  RotateLeftOutlined,
  RotateRightOutlined,
  ZoomInOutlined,
  ZoomOutOutlined,
  RedoOutlined,
  EyeOutlined,
} from '@ant-design/icons';

export interface Position {
  height: number;
  width: number;
  x: number;
  y: number;
}

export interface ImageViewerProps {
  imageUrl: string;
  position?: Position;
  similarity?: number;
  className?: string;
  style?: React.CSSProperties;
  showControls?: boolean;
}

const ImageViewer: React.FC<ImageViewerProps> = ({
  imageUrl,
  position,
  similarity,
  className = '',
  style = {},
  showControls = true,
}) => {
  const imgRef = useRef<HTMLImageElement>(null);
  const containerRef = useRef<HTMLDivElement>(null);
  const [boxStyle, setBoxStyle] = useState<React.CSSProperties>({});
  const [scale, setScale] = useState(1);
  const [rotation, setRotation] = useState(0);
  const [showMarkers, setShowMarkers] = useState(true);
  const [imageLoaded, setImageLoaded] = useState(false);
  const [naturalSize, setNaturalSize] = useState({ width: 0, height: 0 });

  // 计算人脸框的相对位置和尺寸
  const calculateBoxStyle = () => {
    const img = imgRef.current;
    if (!img || !position) {
      setBoxStyle({});
      return;
    }

    // 获取图片的自然尺寸和当前显示尺寸
    const naturalWidth = naturalSize.width || img.naturalWidth;
    const naturalHeight = naturalSize.height || img.naturalHeight;
    const currentWidth = img.offsetWidth;
    const currentHeight = img.offsetHeight;

    // 如果自然尺寸为0，说明图片还未加载完成
    if (naturalWidth === 0 || naturalHeight === 0) {
      return;
    }

    // 计算缩放比例
    const scaleX = currentWidth / naturalWidth;
    const scaleY = currentHeight / naturalHeight;

    // 转换坐标和尺寸
    const x = position.x * scaleX;
    const y = position.y * scaleY;
    const width = position.width * scaleX;
    const height = position.height * scaleY;

    setBoxStyle({
      position: 'absolute',
      left: `${x}px`,
      top: `${y}px`,
      width: `${width}px`,
      height: `${height}px`,
      border: '2px solid #ff4d4f',
      borderRadius: '4px',
      boxSizing: 'border-box',
      pointerEvents: 'none',
      zIndex: 10,
      boxShadow: '0 0 0 1px rgba(255, 255, 255, 0.3) inset',
    });
  };

  // 图片加载完成时计算
  useEffect(() => {
    const img = imgRef.current;
    if (img) {
      img.addEventListener('load', handleImageLoad);
    }
    return () => {
      if (img) {
        img.removeEventListener('load', handleImageLoad);
      }
    };
  }, [imageUrl]);

  const handleImageLoad = () => {
    const img = imgRef.current;
    if (img) {
      setNaturalSize({
        width: img.naturalWidth,
        height: img.naturalHeight,
      });
      setImageLoaded(true);
      calculateBoxStyle();
    }
  };

  // 窗口大小变化、缩放、旋转时重新计算
  useEffect(() => {
    calculateBoxStyle();
  }, [position, scale, rotation, showMarkers, naturalSize]);

  // 监听窗口大小变化
  useEffect(() => {
    window.addEventListener('resize', calculateBoxStyle);
    return () => {
      window.removeEventListener('resize', calculateBoxStyle);
    };
  }, []);

  const handleZoomIn = () => {
    setScale(prev => Math.min(prev + 0.1, 3));
  };

  const handleZoomOut = () => {
    setScale(prev => Math.max(prev - 0.1, 0.5));
  };

  const handleRotateLeft = () => {
    setRotation(prev => (prev - 90) % 360);
  };

  const handleRotateRight = () => {
    setRotation(prev => (prev + 90) % 360);
  };

  const handleReset = () => {
    setScale(1);
    setRotation(0);
  };

  const toggleMarkers = () => {
    setShowMarkers(prev => !prev);
  };

  // 计算容器样式
  const containerStyle: React.CSSProperties = {
    position: 'relative',
    display: 'inline-block',
    overflow: 'hidden',
    border: '1px solid #f0f0f0',
    borderRadius: 8,
    backgroundColor: '#fafafa',
    maxWidth: '100%',
    ...style,
  };

  // 计算图片样式
  const imgStyle: React.CSSProperties = {
    display: 'block',
    width: '100%',
    height: 'auto',
    transform: `rotate(${rotation}deg) scale(${scale})`,
    transition: 'transform 0.3s ease',
    transformOrigin: 'center center',
  };

  // 检查是否有相似度数据
  const hasSimilarity = similarity !== undefined && similarity !== null;

  return (
    <div className={className}>
      <div ref={containerRef} style={containerStyle}>
        {!imageLoaded && (
          <div style={{
            display: 'flex',
            justifyContent: 'center',
            alignItems: 'center',
            height: 200
          }}>
            <Spin tip="图片加载中..." />
          </div>
        )}
        <img
          ref={imgRef}
          src={imageUrl}
          alt="原始图片"
          style={{
            ...imgStyle,
            visibility: imageLoaded ? 'visible' : 'hidden'
          }}
          onLoad={handleImageLoad}
          onError={() => setImageLoaded(false)}
        />
        {position && showMarkers && (
          <>
            <div style={boxStyle} />
            {/* 相似度标签 - 只在有相似度数据时显示 */}
            {hasSimilarity && (
              <div
                style={{
                  position: 'absolute',
                  left: `${parseInt(boxStyle.left as string) || 0}px`,
                  top: `${(parseInt(boxStyle.top as string) || 0) - 25}px`,
                  backgroundColor: '#ff4d4f',
                  color: 'white',
                  padding: '2px 6px',
                  borderRadius: 4,
                  fontSize: '12px',
                  fontWeight: 'bold',
                  pointerEvents: 'none',
                  zIndex: 11,
                }}
              >
                相似度: {(similarity * 100).toFixed(1)}%
              </div>
            )}
          </>
        )}
      </div>

      {showControls && (
        <>
          <div style={{ marginTop: 12, display: 'flex', justifyContent: 'center', gap: 8 }}>

            {position && (
              <Tooltip title={showMarkers ? '隐藏标记' : '显示标记'}>
                <Button
                  icon={<EyeOutlined />}
                  size="small"
                  type={showMarkers ? 'primary' : 'default'}
                  onClick={toggleMarkers}
                />
              </Tooltip>
            )}
          </div>

          {/* {position && (
            <div style={{ marginTop: 8, fontSize: 12, color: '#666', textAlign: 'center' }}>
              原始尺寸: {naturalSize.width} × {naturalSize.height} px
              <br />
              检测到人脸位置: x={position.x}, y={position.y},
              宽度={position.width}, 高度={position.height}
              {hasSimilarity && `, 相似度: ${(similarity * 100).toFixed(1)}%`}
            </div>
          )} */}
        </>
      )}
    </div>
  );
};

export default ImageViewer;
